package com.woniu.work.Service;

import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @program: ECP
 * @description:
 * @create: 2024-11-25 09:27
 **/
@Service
public class ZfOrderService {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    /** 部署流程定义
     *
     * @return
     */
    public String deployProcessDefinition() {
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/order/OrderApplication.bpmn20.xml")
                .name("分销商订单申请流程")
                .deploy();
        return deployment.getId();
    }

    /**
     * 创建并启动流程实例
     */
    public String startProcessInstance(String processDefinitionKey, Map<String, Object> variables) {
        return runtimeService.startProcessInstanceByKey(processDefinitionKey, variables).getId();
    }

    /** 查询用户的待办任务
     *
     * @param assignee
     * @return
     */
    public List<Task> getUserTasks(String assignee) {
        return taskService.createTaskQuery().taskAssignee(assignee).list();
    }

    // 完成任务
    public void completeTask(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }

    // 根据任务 ID 查询任务
    public Task getTaskById(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    // 退回流程
    public void rollbackTask(String taskId, String reason) {
        // 可实现退回逻辑，例如撤销任务、或者将任务回退至某一节点
        Task task = getTaskById(taskId);
        if (task != null) {
            // 可在这里调用特定服务实现回退，例如 signal 方式
            taskService.setVariable(taskId, "rejectedReason", reason);
        }
    }
}